<!-- 章节练习 -->
<template>
  <div class="chapterExercises-page">
    <div class="theory-box">
      <div class="theory-box-l">

        <el-tree
            :data="treeList"
            :props="defaultProps"
            :default-expanded-keys="defaultExpandedKeys"
            node-key="id"
            :render-content="renderContent"
            @node-click="handleNodeClick">
        </el-tree>
<!--        <div class="theory-box-l-title">基础知识</div>-->
<!--        <div style="margin-bottom: 20px">-->
<!--          <el-tree-->
<!--              :data="data"-->
<!--              :props="defaultProps"-->
<!--              :style="{ '&#45;&#45;tree-node-color': checkedNodeFontColor }"-->
<!--              @node-click="handleNodeClick">-->
<!--          </el-tree>-->
<!--        </div>-->
<!--        <div class="theory-box-l-title">基础知识</div>-->
<!--        <div>-->
<!--            <el-tree-->
<!--                :data="data"-->
<!--                :props="defaultProps"-->
<!--                :style="{ '&#45;&#45;tree-node-color': checkedNodeFontColor }"-->
<!--                @node-click="handleNodeClick">-->
<!--            </el-tree>-->
<!--            </div>-->
      </div>
      <div class="theory-box-r">
        <div class="ExamPractice-page" id="chatScrollBox">
<!--          <div class="ExamPractice-head">{{Qsindex + 1}}/{{list.length}}</div>-->
          <div class="examPractice-box" v-for="(item, index) in list">
            <div class="examPractice-box-t">
              <span class="box-t-title">{{index+1}}、【{{item.question.type_name}}】{{ item.question.title }}</span>
              <img src="@/assets/icon/star.png" alt="" v-if="item.is_fav == 0" @click="clickToBookmark(item)">
              <img src="@/assets/icon/star-active.png" alt="" v-if="item.is_fav == 1" @click="clickToBookmark(item)">
            </div>
            <div class="examPractice-box-c">
              <div class="box-c-exam">
                <div class="box-c-exam-item" v-for="(qitem, qindex) in item.question.option"  @click="slectAn(index, qindex)">
                  <div class="check-up" :class="{ checkActive: isSelect(item, item.answer, getIndex(qindex))}">
                    <div class="check-active-in"></div>
                  </div>
                  <div :class="{ active: isSelect(item, item.answer, getIndex(qindex))}">
                    <span class="">{{ getIndex(qindex) }}、</span>
                    <span>{{ qitem.content }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="examPractice-box-b">
              <div class="box-b-btn-ss">
                <div class="box-b-btn" @click="handelClick(item)">解 析</div>
                <div class="box-b-btn-q" @click="multiNext(1)" v-if="item.question_type == '2'">确认</div>
              </div>
              <div class="box-b-content" v-if="item.question.analysisShow">
                <div class="box-b-content-t">正确答案：{{ item.question.answer}}</div>
                <div class="box-b-content-b"><span class="span1">解析︰</span><span v-html="item.question.analysis"></span></div>
              </div>
            </div>
          </div>
<!--          <div class="subject_box-bt-l">-->
<!--            <div class="subject_box-bt-r-btn" @click="multiNext(2)">下一题</div>-->
<!--            <div class="subject_box-bt-r-btn" style="margin-right: 10px" @click="multiPrevious">上一题</div>-->
<!--          </div>-->
          <!--    <el-empty v-else description="暂无数据"></el-empty>-->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ExamPractice from '@/components/ExamPractice'
import {
  favoriteTopic,
  getNestedData,
  getResultAnswer,
  getSimulateDetail,
  getSimulatedExam,
  getStartAnswer,
  getSubmitAnswer, getSubmitTheTestPaper
} from '@/api'
export default {
  name: "chapterExercises",
  components: {
    ExamPractice
  },
  data() {
    return {
      checkedNodeFontColor: '#FF0000', // 选中节点的字体颜色
      Qsindex: 0,
      Qnum: 0,
      data: [
        {
            label: '一、职业道德',
            children: [
                {label: '1、职业道德基础知识'},
                {label: '2、职业守则'},
            ]
          },
        { label: '二、消防工作概述'},
        { label: '三、建筑防火基本知识'},
        { label: '四、燃烧和火灾基本知识'}
      ],
      treeList: [],
      list: [],
      paperId: 0,
      recordId: null,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      defaultExpandedKeys: [],
      ids: ''
    }
  },

  mounted() {
    this.ids = this.$route.query.id
    this.getNestedData()
  },
  methods: {
    getLastLevelKeys(nodes) {
      let keys = [];
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          keys = keys.concat(this.getLastLevelKeys(node.children));
        } else {
          keys.push(node.id); // 假设 label 就是 key，实际情况下可能需要根据实际情况调整
        }
      });
      return keys;
    },
    // 获取节点
    getNestedData() {
      getNestedData({ outline_type: 1 }).then(res => {
        this.treeList = res.data
        let params = {
          outline_id: ''
        }
        if (this.ids) {
          params.outline_id = this.ids
          this.defaultExpandedKeys = [Number(this.ids)]
        } else {
          let id = this.getLastLevelKeys(this.treeList)[0];
          this.defaultExpandedKeys = [id]
          params.outline_id = id
        }
        if (res.data.length == 0) {
          return
        }
        getSimulatedExam(params).then(res=> {
          if (res.code == 1) {
            this.paperId = res?.data?.list?.data[0]?.paper_id || ''
            if (this.paperId) {
              this.getDetail(this.paperId)
            }
          }
        })
      })
    },
    // 点击节点获取题目
    handleNodeClick(data, node) {
      // 如果当前节点是最后一级，则执行点击操作
      if (node.level == 3) {
        let params = {
          outline_id: data.id
        }
        getSimulatedExam(params).then(res=> {
          if (res.code == 1) {
            this.paperId = res?.data?.list?.data[0]?.paper_id || ''
            if (this.paperId) {
              this.getDetail(this.paperId)
            }
          }
        })
      } else {
        // 如果不是最后一级，则阻止向上冒泡，不执行任何操作
        return false;
      }
    },

    // 获取模拟考试题目
    getDetail(id) {
      let params = {
        paper_id: id
      }
      getStartAnswer(params).then(res=> {
        if (res.code == 1) {
          this.Qnum++
          this.recordId = res.data.detail.record_id
          this.list = res.data.detail.question.map((item)=> {
            if (item.answer_state == 2) {
              item.question.analysisShow = true
            } else {
              item.question.analysisShow = false
            }
            return {
              ...item,
            }
          })

          let arr = this.list[this.Qsindex]
          if (arr.answer_state == 1 && this.Qnum !== 1) {
            setTimeout(() => {
              if (this.Qsindex < this.list.length - 1) {
                this.Qsindex = this.Qsindex + 1;
              }
            }, 400);
          } else {
            if (arr.answer_state == 2) {
              this.list[this.Qsindex].question.analysisShow = true
            } else {
              this.list[this.Qsindex].question.analysisShow = false
            }
          }
          this.$nextTick(() => {
            if (this.Qnum == 1) {
              const index = this.list.findIndex(item => item.answer_state == 0 && !item.answer);
              this.Qsindex = index
              const childs = document.querySelectorAll(".examPractice-box");
              if (childs.length) {
                console.log(childs, 111111)
                const scrollHeight = childs[index].offsetTop
                let div = document.getElementById("chatScrollBox");
                div.scrollTop = scrollHeight - 170
              }
            }
          })

        }
      })
    },
    onchange(e) {
      if (e == 1) {
        if(this.Qsindex != 0) {
          this.Qsindex--
        } else {
          this.Qsindex = 0
        }
      } else {
        if (this.Qsindex + 1 == this.list.length) {
          this.Qsindex == this.list.length
        } else {
          this.Qsindex++
        }
      }
    },

    handelClick(item) {
      item.question.analysisShow = !item.question.analysisShow
    },
    // 选项字母
    getIndex(n) {
      return String.fromCharCode(n + 65)
    },

    isSelect(e, answer, answer2) {
      if (e.question.question_type == 2) {
        return answer.indexOf(answer2) != -1
      } else {
        return answer === answer2
      }
    },
    slectAn(index, n) {
      this.Qsindex = index
      let item = this.list[index];
      if (item.question.question_type != 2) {
        item.answer = this.getIndex(n);
        this.subAnser();
      } else {
        let arr = item.answer || [];
        let currentOptions = this.getIndex(n);
        if (typeof arr == 'string') {
          arr = item.answer.split(',');
        }
        let arrIndex = arr.indexOf(currentOptions);
        if (arrIndex > -1) {
          arr.splice(arrIndex, 1)
        } else {
          arr.push(this.getIndex(n))
        }
        item.answer = arr.join(",")
        // this.subAnser();
      }
    },
    // 点击每题答案提交
    subAnser() {
      // let itemInfo = this.list[this.Qsindex]
      // let answer = this.list[this.Qsindex].answer;
      // let arr = this.list[this.Qsindex].answer.split(',')
      // if (!answer) {
      //   return
      // }
      // if (itemInfo.question.question_type == 2) {
      //   if (arr.length < 2) {
      //     return;
      //   }
      // }

      let that = this;
      let answer = that.list[that.Qsindex].answer;
      if (!answer) {
        // if (this.Qsindex + 1 < this.list.length) {
        //   that.Qsindex--
        // }
        return
      }
      if (that.list[that.Qsindex].question.question_type == 2) {
        if (answer.split(',').length<2) {
          // this.$message.warning('至少选择两个选项！')
          // that.isShow = true
          // if (this.Qsindex + 1 < this.list.length) {
          //   that.Qsindex--
          // }
          return;
        }
      }
      let id = this.list[this.Qsindex].id;
      let params = {
        id: id,
        answer: answer
      }
      getSubmitAnswer(params).then(res => {
        if (res.code == 1) {
          if (res.data.is_submit) {
            this.submitClick()
          }
          this.getDetail(this.paperId)
        }
      })
    },

    /* 上一题*/
    multiPrevious() {
      if (this.Qsindex > 0) {
        this.$emit('onchange', 1)
      }
    },
    /* 下一题 */
    multiNext(n) {
      if (this.Qsindex + 1 < this.list.length) {
        if (n == 1) {
          this.subAnser();
        } else {
          this.$emit('onchange', 2)
        }
      } else {
        this.subAnser();
      }
    },
    // 确认交卷
    submitClick() {
      let params = {record_id: this.recordId}
      getSubmitTheTestPaper(params).then(res => {
      })
    },
    // 点击是否收藏
    clickToBookmark(item) {
      let params = {
        paper_id: this.paperId,
        question_id: item.question_id,
        paper_question_id: item.paper_question_id,
      }
      favoriteTopic(params).then(res => {
        if (res.code == 1) {
          item.is_fav = !item.is_fav
        }
      })
    },
    renderContent(h, { node, data }) {
      if (node.level == 3) {
        return (
            <span>
              <i class="el-icon-document" style="margin-right: 4px;"></i> {node.label}
            </span>
        );
      } else {
        return (
            <span>
              <i class="el-icon-folder" style="margin-right: 4px;"></i> {node.label}
            </span>
        );
      }
      // if (node.childNodes && node.childNodes.length>0 || node.level == 1) {
      //   return (
      //       <span>
      //         <i class="el-icon-folder" style="margin-right: 4px;"></i> {node.label}
      //       </span>
      //   );
      // } else {
      //   return (
      //       <span>
      //         <i class="el-icon-document" style="margin-right: 4px;"></i> {node.label}
      //       </span>
      //   );
      // }
    },

  }
}
</script>

<style lang="scss" scoped>
.chapterExercises-page {
  width: 100%;
  height: 100%;
  ::v-deep .el-tree .el-tree-node__content {
    padding:3px 0;
  }
  /* 覆盖被选中节点的字体颜色 */
  ::v-deep .el-tree .el-tree-node__content:hover {
    color: #409EFF; /* 更改为你想要的颜色 */
  }
  ::v-deep .el-tree-node:focus>.el-tree-node__content {
    color: #409EFF!important;
  }

  .ExamPractice-page {
    width: 100%;
    height: 100%;
    overflow-y: scroll;
    scrollbar-width: none;
    scrollbar-color: transparent transparent;
    font-family: PingFang SC, PingFang SC;
    .active {
      color: #3582E5;
    }
    .check-up {
      width: 14px;
      height: 14px;
      border-radius: 50%;
      border: 1px solid #9F9F9F;
      margin-right: 10px;
    }
    .checkActive {
      width: 14px;
      height: 14px;
      border-radius: 50%;
      border: 1px solid #9F9F9F;
      margin-right: 10px;
      .check-active-in {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin: 2px auto;
        background: #3582E5;
        border: 1px solid #3582E5;
      }
    }
    .ExamPractice-head {
      text-align: center;
      margin-bottom: 10px;
      color: #666666;
    }
  }
}
</style>
